package com.ruowei.modules.sys.utils;

import com.ruowei.common.error.exception.CommonException;
import com.ruowei.modules.member.domain.Member;
import com.ruowei.modules.member.repository.MemberRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AppletTokenUtils {

    private static RedisUtil redisUtil;
    private static MemberRepository memberRepository;

    public AppletTokenUtils(RedisUtil redisUtil, MemberRepository memberRepository) {
        AppletTokenUtils.redisUtil = redisUtil;
        AppletTokenUtils.memberRepository = memberRepository;
    }

    public static Member getOpenIdByToken(HttpServletRequest request) {
        String appletToken = request.getHeader("AppletToken");
        if (StringUtils.isEmpty(appletToken)) {
            throw new CommonException("未登录或登录失效");
        }
        if (redisUtil.get(appletToken) == null) {
            throw new CommonException("未登录或登录失效");
        }
        String openId = redisUtil.get(appletToken).toString();
        if (StringUtils.isEmpty(openId)) {
            throw new CommonException("未登录或登录失效");
        }
        return memberRepository.findByOpenId(openId).orElseThrow(() -> new CommonException("未找到该用户"));
    }
}
